<?php

/*
  Author:    Alfredo 'IceCoder' Mungo <chimeranet89@gmail.com>
  License:   LGPL
  Copyright: 2013
*/

/*
  CHECK FUNCTION SPECIFICATION:

  Check functions must begin their name with the 'check' prefix.
  Check functions must return true or false (respectively on success or failure).
*/

define('DEBUG', false);

if(DEBUG) {
  error_reporting(E_ALL);
  ini_set('display_errors', '1');
}

$tests = array(
	       'PHP version' => 'checkPHPVersion',
	       'Read/Write permissions' => 'checkPerms',
	       'GD library' => 'checkGD'
	       );

$result = array();

function doChecks() {
  foreach($GLOBALS['tests'] as $k => $f)
    doCheck($k, $f);
}

function doCheck($title, $f) {
  if(is_callable($f))
    $GLOBALS['result'][$title] = $f();
}

function checkGD() {
  $res = defined('GD_VERSION');
  return $res;
}

function checkPHPVersion() {
  $v = phpversion();
  $v = explode('.', $v);
  $v = ($v[0] >= 5) && ($v[1] >= 3);

  return $v;
}

function checkPerms() {
  $perms = fileperms('index.php');

  if($perms & 0x0180) // rw* *** ***
    return true;
  else
    return false;
}

if(isset($_GET['test']))
   doChecks();

?><!DOCTYPE html>
<html>
<head>
  <title>PHI Framework pre-installation script</title>
  <style type="text/css">
    a { color: blue; }
    a { text-decoration: none; font-weight: 600; }
    table { margin-bottom: 40px; font-family: monospace; font-size: larger; }
    td { padding-left: 40px; padding-right: 40px; }
    div { padding-left: 20px; }
    .test-result { font-weight: bold; background-color: #eee; text-align: center }
    .not-executed { color: orange; }
    .executed-failed { color: red; }
    .executed-passed { color: green; }
  </style>
</head>
<body>
  <h1>PHI Framework</h1>
  <div>
    <h2>Pre-installation script</h2>
    <div>
      <?php if(isset($_GET['test'])): ?>
      <p>Performed <b><?=count($result)?></b> tests of <b><?=count($tests)?></b></p>
      <?php endif ?>
      <table><?php
	if(count($result) === 0)
	  foreach($tests as $tname => $tfun)
	    echo "<tr><td>$tname<td class=\"test-result not-executed\">Not executed";
	  else
	    foreach($result as $tname => $tres)
	      echo "<tr><td>$tname<td class=\"test-result " . ($tres? 'executed-passed">PASSED': 'executed-failed">FAILED');
      ?></table>
      <?php if(!isset($_GET['test'])): ?>
      <a href="?test" title="Run tests">Run tests</a>
      <?php elseif(count($result) === count($tests)): ?>
      <a href="install.php" title="Proceed to installation">Proceed to installation</a><br>
      <a href="?test" title="Run tests again">Run again</a><br>
      <p><b style="font-weight: 900">NB: </b><i>If you proceed to the installation step without passing all the tests, the framework might not work as expected.</i></p>
      <?php endif ?>
    </div>
  </div>
</body>
</html>
